package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ExportPDF;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.MembersMapper;
import com.ruoyi.system.domain.Members;
import com.ruoyi.system.service.IMembersService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 系统会员信息Service业务层处理
 * 
 * @author 陈斌斌
 * @date 2025-09-17
 */
@Service
@RequiredArgsConstructor
public class MembersServiceImpl extends ServiceImpl<MembersMapper ,Members> implements  IMembersService
{
    private final MembersMapper membersMapper;
    private final ExportPDF exportPDF;
    private final SysDictDataMapper sysDictDataMapper;
    private final IOrderService orderService;
    /**
     * 查询系统会员信息
     * 
     * @param id 系统会员信息主键
     * @return 系统会员信息
     */
    @Override
    public Members selectMembersById(String id)
    {
       if(isEmpty(id)){
           throw new RuntimeException("主键标识不能为空");
       }
        return this.baseMapper.selectById(id);
    }

    /**
     * 查询系统会员信息列表
     * 
     * @param members 系统会员信息
     * @return 系统会员信息
     */
    @Override
    public List<Members> selectMembersList(Members members)
    {
        return membersMapper.selectMembersList(members);
    }

    /**
     * 新增系统会员信息
     * 
     * @param members 系统会员信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertMembers(Members members)
    {
        Members member = membersMapper.selectMembersByFullName(members.getFullName());
        members.setStatus("0");
        return  StringUtils.isNotNull(member)?this.baseMapper.insert(members):0;

    }

    /**
     * 修改系统会员信息
     * 
     * @param members 系统会员信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMembers(Members members)
    {
        if(isEmpty(members.getId())){
            throw new RuntimeException("主键标识不能为空");
        }
        if (isEmpty(members.getBalance())){
            if (members.getPointsBalance()<0){
                members.setPointsBalance(0L);
            }
            return this.baseMapper.updateById(members);
        }
        else{
        Order order = new Order();
        order.setMId(members.getId());
         order.setId( orderService.selectByLast().getId());
            this.baseMapper.updateById(members);
       return orderService.updateOrder(order);

    }
    }



    /**
     * 删除系统会员信息信息
     * 
     * @param id 系统会员信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteMembersById(String id)
    {
        if(isEmpty(id)){
            throw new RuntimeException("主键标识不能为空");
        }
        return this.baseMapper.deleteById(id);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String importMembers(List<Members> membersList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(membersList) || membersList.isEmpty())
        {
            throw new ServiceException("导入会员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Members members : membersList)
        {
            try
            {
                // 验证性别
                String gender = members.getGender();
                if (!"0".equals(gender) && !"1".equals(gender) && !"2".equals(gender)) {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、会员 ")
                            .append(members.getFullName()).append(" 性别填写有误");
                    break; // 或者根据你的循环结构调整
                }

                // 验证状态
                String status = members.getStatus();
                if (!"0".equals(status) && !"1".equals(status)) {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、会员 ")
                            .append(members.getFullName()).append(" 激活状态填写有误");
                    break;
                }


                // 验证是否存在这个用户
                Members member = membersMapper.selectMembersByFullName(members.getFullName());
                if (StringUtils.isNull(member))
                {
                    this.membersMapper.insert(members);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、会员 " + members.getFullName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    members.setId(member.getId());
                    this.baseMapper.updateById(members);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、会员 " + members.getFullName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、会员 " + members.getFullName() + " 已存在");
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、会员 " + members.getFullName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void exportPdf(HttpServletRequest request, HttpServletResponse response,String fileName,List<Members> list) {
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 导出的结果集
        List<String> lists = new ArrayList<String>(0);
        if (list != null && !list.isEmpty()) {
              for(Members members : list){
                  lists.add(members.getFullName());
                  lists.add(members.getPhone());
                  lists.add(sysDictDataMapper.selectDictLabel("sys_user_sex",members.getGender()));
                  lists.add(String.valueOf(members.getPointsBalance()));
                  lists.add(sysDictDataMapper.selectDictLabel("m_status",members.getStatus()));
                  lists.add(members.getRemark());
                  lists.add(sdf.format(members.getCreateTime()));
                  lists.add(sdf.format(members.getUpdateTime()));
                  lists.add(members.getCreateBy());
                  lists.add(members.getUpdateBy());

              }
            try {
                exportPDF.createPDF(fileName, "会员信息统计明细表",lists, Members.listNames, request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private boolean isEmpty(String id)
    {
        return StringUtils.isEmpty(id);
    }
}
